package com.ccp.dev.system.service;
import com.ccp.dev.core.basic.base.BaseService;
import com.ccp.dev.core.basic.util.UUIDUtils;
import com.ccp.dev.core.basic.web.query.QueryFilter;
import com.ccp.dev.core.util.StringUtil;
import com.ccp.dev.core.util.UniqueIdUtil;
import com.ccp.dev.system.dao.MessageReceiverDao;
import com.ccp.dev.system.dao.MessageSendDao;
import com.ccp.dev.system.model.MessageReceiver;
import com.ccp.dev.system.model.MessageSend;
import com.ccp.dev.system.model.SysUser;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * 发送消息 Service类
 * @author csx
 * @Date 2012-01-14 15:10:58
 */
@Service
public class MessageSendService extends BaseService<MessageSend> {
	@Resource
	private MessageSendDao dao;
	@Resource
	private MessageReceiverDao messageReceiverDao;
	@Resource
	private MessageReadService messageReadService;


	public MessageSendService() {

	}

	/**
	 * 查询某个用户的接收消息
	 *
	 * @param queryFilter
	 * @return List<MessageSend>
	 */
	@Transactional(rollbackFor = Exception.class)
	public List<MessageSend> getReceiverByUser(QueryFilter queryFilter) {
		return dao.getReceiverByUser(queryFilter);
	}

	/**
	 * 根据id查询发送消息
	 *
	 * @param id
	 * @return MessageSend
	 */
	public MessageSend getById(String id) {
		return dao.getById(id);
	}

	/**
	 * 保存【发送消息MessageSend】数据，同时插入【接收消息：MessageReceiver】数据
	 *
	 * @param messageSend
	 * @param curUser
	 */
	@Transactional(rollbackFor = Exception.class)
	public void addMessageSend( MessageSend messageSend,SysUser curUser) {
		// 插入MessageSend
		String receiverName = messageSend.getReceiverName();
		String receiverOrgName = messageSend.getReceiverOrgName();
		String receiverId = messageSend.getReceiverId();
		String receiverOrgId = messageSend.getReceiverOrgId();
		//发送消息的接收人拼接（因为messageSend数据库表不存在receiverOrgName字段属性，所以要拼接到receiverName属性中）
		if (receiverOrgName.length() > 0 ) {
			if(receiverName.length() > 0) {
				messageSend.setReceiverName(receiverName + "," + receiverOrgName);
			}else{
				messageSend.setReceiverName(receiverOrgName);
			}
		}
		String messageId = null;
		// 保存 SYS_MSG_SEND 建立用户与发送消息的联系
		if (StringUtil.isEmpty(messageSend.getId())){
			messageId = UUIDUtils.getUUIDFor32();
			messageSend.setId(messageId);
			dao.add(messageSend);
		} else {
			messageId = messageSend.getId();
			dao.update(messageSend);
			//撤销所有原已发送的消息
			messageReceiverDao.delByMessageId(messageId);
		}
		String[] idArr = receiverId.split(",");
		String[] nameArr = receiverName.split(",");
		String[] orgIdArr = receiverOrgId.split(",");
		String[] orgNameArr = receiverOrgName.split(",");
		// 插入 Sys_Msg_Receiver 建立用户与收到消息的联系
		if (receiverId.length() > 0) {
			addReceiver(idArr, messageId, MessageReceiver.TYPE_USER, nameArr,messageSend.getJsonFile());
		}
		if (receiverOrgId.length() > 0) {
			addReceiver(orgIdArr, messageId, MessageReceiver.TYPE_ORG, orgNameArr,messageSend.getJsonFile());
		}
	}

	/**
	 * 新增消息接收者方法
	 * @param id
	 * @param messageId
	 * @param type
	 * @param name
	 */
	@Transactional(rollbackFor = Exception.class)
	public void addReceiver(String[] id, String messageId, Short type, String[] name,String jsonFile) {
		for (int i = 0; i < id.length; i++) {
			//过滤用户,查询用户是否已接受了该消息
			if (messageReceiverDao.getByMessageIdAndReceiverId(messageId, id[i]) == null) {
				MessageReceiver messageReceiver = new MessageReceiver();
				if (StringUtil.isNotEmpty(id[i])) {
					messageReceiver.setReceiverId((id[i]));
					if (id.length > i) {
						messageReceiver.setReceiver(name[i]);
					}
					messageReceiver.setReceiveType(type);
				}
				messageReceiver.setId(UUIDUtils.getUUIDFor32());
				messageReceiver.setMessageId(messageId);
				messageReceiver.setIsDelete(MessageReceiver.NOTDELETE);
				messageReceiver.setJsonFile(jsonFile);
				messageReceiverDao.add(messageReceiver);
			}
		}
	}

	/**
	 * 添加只有一个接受者的站内消息
	 * @param messageSend
	 */
	@Transactional(rollbackFor = Exception.class)
	public void addMessageSend(MessageSend messageSend) {
		dao.add(messageSend);
		MessageReceiver receiver = new MessageReceiver();
		receiver.setCreateBy(messageSend.getCreateBy());
		receiver.setCreateTime(new Date());
		receiver.setId(UUIDUtils.getUUIDFor32());
		receiver.setMessageId(messageSend.getId());
		receiver.setReceiverId(messageSend.getRid());
		receiver.setReceiveType(MessageReceiver.TYPE_USER);
		receiver.setReceiver(messageSend.getReceiverName());
		messageReceiverDao.add(receiver);
	}

	/**
	 * 将删除标识字段设置为1，做逻辑删除
	 * @param ids
	 */
	@Transactional(rollbackFor = Exception.class)
	public void updateStatus(String[] ids) {
		Map<String, Object> params = new HashMap<>();
		params.put("ids", ids);
		dao.updateStatus(params);
	}

	/**
	 * 发信人在已发送消息界面删除信息
	 * @param lAryId
	 */
	@Transactional(rollbackFor = Exception.class)
	public void deleteMessage(String[] lAryId){
		//先将已发送消息中的数据进行删除
		this.delByIdArray(lAryId);
		//再将收到的消息中的数据进行删除
		this.messageReceiverDao.delByIdArray(lAryId);
		//再将接收时间表中的数据进行删除
		this.messageReadService.delByIdArray(lAryId);
	}
}
